package com.alkin.thing.framework.security.service;

import com.alkin.thing.common.constant.Constants;
import com.alkin.thing.common.exception.CustomException;
import com.alkin.thing.common.exception.user.CaptchaException;
import com.alkin.thing.common.exception.user.CaptchaExpireException;
import com.alkin.thing.common.exception.user.UserPasswordNotMatchException;
import com.alkin.thing.common.utils.MessageUtils;
import com.alkin.thing.common.utils.ServletUtils;
import com.alkin.thing.common.utils.StringUtils;
import com.alkin.thing.framework.manager.AsyncManager;
import com.alkin.thing.framework.manager.factory.AsyncFactory;
import com.alkin.thing.framework.redis.RedisCache;
import com.alkin.thing.framework.security.LoginUser;
import com.alkin.thing.framework.security.config.AppLoginConfig;
import com.alkin.thing.project.system.domain.SysUser;
import com.alkin.thing.project.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author huangzy
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AppLoginConfig appLoginConfig;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {

        boolean validateCaptcha = true;
        String consoleType = ServletUtils.getRequest().getHeader("ConsoleType");
        // 是否是app端请求
        boolean isAppLogin = StringUtils.isNotEmpty(consoleType) && consoleType.equals("app");
        if (isAppLogin) {
            //app登录不校验验证码
            validateCaptcha = false;

            // 判断app账号登录数量是否超出
            validateAppLogin(username);
        }

        if (validateCaptcha) {
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        if (isAppLogin) {
            // 记录用户表中，用户使用过app登录
            sysUserMapper.setAppLoginFlag(username);
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        String token = tokenService.createToken(loginUser);

        return token;
    }

    private void validateAppLogin(String userName) {
        // 判断app账号登录数量是否超出
        Integer limit = appLoginConfig.getLoginUserLimit(); //获取配置的app账号登录限制数量
        if (limit == null) {
            return;
        }
        SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
        if (sysUser != null && SysUser.APP_LOGIN_FLAG_Y.equals(sysUser.getAppLoginFlag())) {
            return;
        }
        int count = sysUserMapper.countByAppLoginFlag();
        if (count >= limit) {
            throw new CustomException("app登录账户数量已达上限" + limit + "，登录失败");
        }
    }

}
